package com.example.javabasic.thread.classtwo.lock.demo1;

//读写锁
public class ReadWriteLock {

    //读的线程个数
    private int readingReaders = 0;
    //想读  但是读不了的线程个数
    private int waitingReaders = 0;
    //正在写的线程数
    private int writingWrites = 0;
    //想写  等待写的线程数
    private int waitingWrites = 0;
    //偏心  true: 更喜欢写操作  false:更喜欢读
    private boolean perferWriter = true;

    public ReadWriteLock() {
        this(true);
    }

    public ReadWriteLock(boolean perferWriter) {
        this.perferWriter = perferWriter;
    }

    //读锁
    public synchronized void readLock() throws InterruptedException {
        this.waitingReaders++;
        try{
            //如果 有人正在写, 则不能读,线程阻塞
            while(writingWrites>0||(perferWriter&& waitingWrites>0)){
                this.wait();
            }
            //正在读的个数 +1
            readingReaders++;
        }finally{
            //等待读的线程数 --
            waitingReaders-- ;
        }

    }

    //释放读锁
    public synchronized void readUnlock(){
        //正在读的 --
        this.readingReaders--;
        this.notifyAll();
    }

    //写锁
    public synchronized void writeLock() throws InterruptedException {
        //等待写的+1
        this.waitingWrites++;
        try{
            //当 正在读的>0  或者正在写的>0   则阻塞
            while(readingReaders>0 || writingWrites>0){
                this.wait();
            }
            //写的+1
            this.writingWrites++;
        }finally{
            //等待写的-1
            this.waitingWrites--;
        }

    }
    //释放写锁
    public synchronized void writeUnLock(){
        //写操作完成 正在写-1
        this.writingWrites--;
        //通知其他线程可以操作了
        this.notifyAll();
    }

}
